package cn.itsource.shiro.sessionManager;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 重写Session管理器,需要在shiro.xml中配置
 * @author xjh
 * @date 2020/3/30 21:56
 */
public class CrmSessionManager extends DefaultWebSessionManager {
    //设置前台传过来的jsessionid 到shiro的session里面去
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        /*取出名为X-TOKEN的jsessionid*/
        String sessionId = WebUtils.toHttp(request).getHeader("X-TOKEN");
        HttpServletRequest req = (HttpServletRequest) request;
        if(!StringUtils.isEmpty(sessionId)){
            /*默认,不管*/
            req.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "Stateless request");
            /*取出来的jsessionid存到这里*/
            req.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            /*默认,不管*/
            req.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }else {
            return super.getSessionId(request, response);
        }
    }
}